package com.dg11185.nearshop.activity.setting;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.nearshop.R;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.dg11185.libs.autoupdate.Version;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.utils.file.FileUtils;
import com.dg11185.nearshop.activity.BaseFragment;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.baidumap.MapConstant;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.request.GetLatestVersionRequest;
import com.dg11185.nearshop.view.MyAlertDialog;
import com.dg11185.nearshop.view.SwitchButton;
import com.dg11185.nearshop.view.SwitchButton.OnSwitchButtonChangeListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.message.PushAgent;
import com.umeng.update.UmengUpdateAgent;
import com.wlper.lib.uitls.ViewUtils;

/**
 * 更多主页面
 * 
 * @author：Daibo
 * @time：2014-5-11 下午6:07:59
 */
public class SettingFragment extends BaseFragment implements OnClickListener {

    private TextView cacheSize, versionTxt, offlineTxt;

    private SharedPreferences preferences;

    private SwitchButton isVoiceOpened, isGetLatestNews;

    private MKOfflineMap mOffline = null;

    private MKOLUpdateElement existElement = null;

    private MKOLUpdateElement updataElement = null;

    private MyAlertDialog dialog = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getActivity().findViewById(R.id.setting_main_voice).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_latest).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_update_version).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_map).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_help).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_feedback).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_about_us).setOnClickListener(this);
        getActivity().findViewById(R.id.setting_main_clear_disk).setOnClickListener(this);
        isVoiceOpened = (SwitchButton) getActivity().findViewById(R.id.more_voice_switch);
        isGetLatestNews = (SwitchButton) getActivity().findViewById(R.id.more_latest_switch);
        isVoiceOpened.setListener(listener);
        isGetLatestNews.setListener(listener);

        cacheSize = (TextView) getActivity().findViewById(R.id.clear_disk);
        versionTxt = (TextView) getActivity().findViewById(R.id.setting_update_version_txt);
        offlineTxt = (TextView) getActivity().findViewById(R.id.setting_update_map_txt);
        initOfflineMap();
    }

    @Override
    public void onResume() {
        super.onResume();

        /**
         * MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
         */
        preferences = getActivity().getSharedPreferences(Constants.preferences_system_setting, Context.MODE_PRIVATE);
        isVoiceOpened.setSwitchState(preferences.getBoolean(Constants.is_open_the_voice, true));
        isGetLatestNews.setSwitchState(preferences.getBoolean(Constants.is_get_push_news, true));

        getCacheFileSize();
        getNetVersion();
        MobclickAgent.onPageStart(this.getClass().getName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getName());
    }

    @Override
    public void onDestroyView() {
        NetClient.httpCancel(mActivity, true);
        super.onDestroy();
    }

    /** 点击 */
    private void clearDisk() {
        String message = "<br><font  size=15sp  color=#000000 > 缓存的作用</font> <br><br> <font size=13sp color=#999999> 1. 节省手机流量，相同数据不会重复加载。  </font> <br> <br><font size=13sp color=#999999> 2. 断网情况下也可以浏览缓存数据。</font> ";
        dialog.setTitle("删除本地缓存").setMessage(Html.fromHtml(message))
                .setPositiveButton("现在删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (FileUtils.deleteDirectory(CacheConstant.getCachePath())) {
                            ViewUtils.showToast(getActivity(), "缓存已清空");
                            getCacheFileSize();
                        }
                        dialog.dismiss();
                    }
                }).setNegativeButton("暂不删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).show();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.setting_main_clear_disk:
            clearDisk();
            break;

        case R.id.setting_main_map:
            onMapClicked();
            break;
        case R.id.setting_main_update_version:
            UmengUpdateAgent.forceUpdate(mActivity);
            break;
        case R.id.setting_main_help:
            startActivity(new Intent(getActivity(), HelpActivity.class));
            break;
        case R.id.setting_main_feedback:
            FeedbackAgent agent = new FeedbackAgent(mActivity);
            agent.startFeedbackActivity();
            break;
        case R.id.setting_main_about_us:
            startActivity(new Intent(mActivity, AboutUs.class));
            break;
        default:
            break;
        }
    }

    private OnSwitchButtonChangeListener listener = new OnSwitchButtonChangeListener() {
        @Override
        public void onChange(SwitchButton sb, boolean state) {
            SharedPreferences.Editor editor = preferences.edit();
            if (sb == isVoiceOpened) {
                editor.putBoolean(Constants.is_open_the_voice, state);
            } else {
                PushAgent mPushAgent = PushAgent.getInstance(mActivity);
                editor.putBoolean(Constants.is_get_push_news, state);
                if (state) {
                    if (!mPushAgent.isEnabled()) {
                        mPushAgent.enable();
                    }
                } else {
                    if (mPushAgent.isEnabled()) {
                        mPushAgent.disable();
                    }
                }
            }
            editor.commit();
        }
    };

    @Override
    public View setContentView() {
        return mInflater.inflate(R.layout.setting_main, null);
    }

    @Override
    public boolean initTopBanner() {
        setTitle("更多");
        return true;
    }

    private void getNetVersion() {
        GetLatestVersionRequest request = new GetLatestVersionRequest();
        request.setActionListener(new GetLatestVersionRequest.ActionListener<Version>() {
            @Override
            public void onSuccess(Version version) {
                PackageManager manager = getActivity().getPackageManager();
                PackageInfo info;
                try {
                    info = manager.getPackageInfo(getActivity().getPackageName(), 0);
                    String versionName = info.versionName;
                    int versionCode = info.versionCode;
                    if (version.versionCode > versionCode) {
                        versionTxt.setText("可更新到" + version.versionName);
                    } else {
                        versionTxt.setText("已是最新版   " + versionName);
                    }
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int resultCode) {
            }
        });
        NetClient.httpGet(request);
    }

    private void getCacheFileSize() {
        File file = new File(CacheConstant.getCachePath());
        cacheSize.setText(FileUtils.getFileSize(FileUtils.getDirSize(file) / 2));
    }

    private void initOfflineMap() {

        mOffline = new MKOfflineMap();
        mOffline.init(new OfflineMapListener());
        initExsitElement();

        if (existElement != null) {
            if (existElement.status == MKOLUpdateElement.FINISHED) {
                offlineTxt.setText(existElement.cityName + ": 已下载");
            }
        }
        dialog = new MyAlertDialog(getActivity());
    }

    private void initExsitElement() {
        try {

            List<MKOLUpdateElement> elements = mOffline.getAllUpdateInfo();
            if (elements != null) {
                for (MKOLUpdateElement e : elements) {
                    if (e.cityID == MapConstant.OFFLINE_CITY_ID) {
                        existElement = e;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onMapClicked() {

        if(updataElement != null){
            return;
        }
        if (existElement == null) {
            startDownload();
        } else {
            if (existElement.status == MKOLUpdateElement.FINISHED) {
                startDelete();
            } else {
                mOffline.start(MapConstant.OFFLINE_CITY_ID);
                offlineTxt.setText("重连服务器中..");
            }
        }
    }

    private void startDownload() {
        String message = "<br><font  size=15sp  color=#000000 > 离线地图的好处</font> <br><br> <font size=13sp color=#999999> 1. 节省90%的手机流量 </font> <br> <br><font size=13sp color=#999999> 2. 地图浏览健步如飞</font> ";
        dialog.setTitle("下载离线地图").setMessage(Html.fromHtml(message))
                .setPositiveButton("马上下载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        mOffline.start(MapConstant.OFFLINE_CITY_ID);
                        offlineTxt.setText("连接服务器..");
                    }
                }).setNegativeButton("暂不下载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private void startDelete() {
        String message = "<br><font  size=15sp  color=#000000 > 离线地图的好处</font> <br><br> <font size=13sp color=#999999> 1. 节省90%的手机流量 </font> <br> <br><font size=13sp color=#999999> 2. 地图浏览健步如飞</font> ";
        dialog.setTitle("删除离线地图").setMessage(Html.fromHtml(message))
                .setPositiveButton("确定删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOffline.remove(MapConstant.OFFLINE_CITY_ID);
                        offlineTxt.setText("未下载.");
                        existElement = null;
                        initExsitElement();
                        dialog.dismiss();
                        if (existElement == null) {
                            ViewUtils.showToast(getActivity(), "删除完成");
                        } else {
                            ViewUtils.showToast(getActivity(), "删除失败");
                        }
                    }
                }).setNegativeButton("暂不删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private class OfflineMapListener implements MKOfflineMapListener {
        @Override
        public void onGetOfflineMapState(int type, int state) {
            switch (type) {
            case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
                updataElement = mOffline.getUpdateInfo(state);
                String total = "";
                if ("".equals(total)) {
                    total = new DecimalFormat("#.##").format(updataElement.serversize / 1000.00 / 1000.00);
                }
                // 处理下载进度更新提示
                if (updataElement != null) {

                    offlineTxt.setText(String.format("%s(%sM) : %d%%", updataElement.cityName, total,
                            updataElement.ratio));
                }
            }
                break;
            case MKOfflineMap.TYPE_NEW_OFFLINE:
                // 有新离线地图安装
                // Log.d("OfflineDemo", String.format("add offlinemap num:%d",
                // state));
                break;
            case MKOfflineMap.TYPE_VER_UPDATE:
                // 版本更新提示
                // MKOLUpdateElement e = mOffline.getUpdateInfo(state);

                break;
            }
        }
    }

}
